package timing.ukulele.storage.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import timing.ukulele.storage.entity.NodeEntity;
import timing.ukulele.storage.service.NodeService;
import timing.ukulele.storage.service.PreviewService;

@RestController
@RequestMapping("/preview")
@Slf4j
@Tag(name = "预览相关操作")
public class PreviewController {

    private final NodeService nodeService;
    private final PreviewService previewService;

    public PreviewController(NodeService nodeService, PreviewService previewService) {
        this.nodeService = nodeService;
        this.previewService = previewService;
    }

    @GetMapping("/{id}")
    @Operation(summary = "pdf预览")
    public void previewFile(@PathVariable("id") String fileId, @RequestHeader("account") String account,
                            HttpServletResponse response) {
        NodeEntity node = nodeService.getNodeById(fileId);
        if (node == null) {
            return;
        }
        // TODO 权限控制
        if ("folder".equalsIgnoreCase(node.getType()) || "unknown".equalsIgnoreCase(node.getType())) {
            return;
        }
        this.previewService.previewFile(node, response);
    }

    @GetMapping("/png/{id}")
    @Operation(summary = "下载Png文件")
    public void getPngFile(@PathVariable("id") String fileId, @RequestHeader("account") String account,
                           HttpServletResponse response) {
        NodeEntity node = nodeService.getNodeById(fileId);
        if (node == null) {
            return;
        }
        // TODO 权限控制
        if ("folder".equalsIgnoreCase(node.getType()) || "unknown".equalsIgnoreCase(node.getType())) {
            return;
        }
        this.previewService.toPng(node, response);
    }

    @GetMapping("/svg/{id}")
    @Operation(summary = "下载Svg文件")
    public void getSvgFile(@PathVariable("id") String fileId, @RequestHeader("account") String account,
                           HttpServletResponse response) {
        NodeEntity node = nodeService.getNodeById(fileId);
        if (node == null) {
            return;
        }
        // TODO 权限控制
        if ("folder".equalsIgnoreCase(node.getType()) || "unknown".equalsIgnoreCase(node.getType())) {
            return;
        }
        this.previewService.toSvg(node, response);
    }
}
